<template>
  <div>
    <el-dialog
      title="任务执行"
      :visible.sync="dialogVisible"
      :modal="true"
      :appendToBody="true"
      width="90%"
      v-dialog-drag
      :close-on-click-modal="false"
      top="5vh"
      :destroy-on-close="true"
      @open="handleOpen"
      @close="handleClose"
    >
      <div class="dialog-content">
        <!-- 显示规则：有执行权限 -->
        <el-button
          v-if="buttonPermi(['taskMgmt:center:transfer'], !disabled && row && row.hasExecPower == 'Y')"
          type="primary"
          plain
          class="transfer-btn"
          size="small"
          @click="handleTransfer"
          >转办</el-button
        >
        <FillForm
          ref="FillForm"
          v-loading="loading"
          :formName="formName"
          :headerForm="headerForm"
          :formFieldConfig="templateConfig"
          :formData="formData"
          :formWorkOrder="formWorkOrder"
          :renderingMode="renderingMode"
          :isGetLastIndexValue="true"
          :disabled="disabled"
        ></FillForm>

        <template v-if="needParticipant">
          <div>
            <el-button v-if="!disabled" type="primary" size="small" @click="addParticipant"
              >选择参与人</el-button
            >
          </div>
          <el-row v-for="(row, i) in participants" :key="i">
            <el-col :span="3"> 参与人：{{ row.realname }} </el-col>
            <el-col :span="12">
              非生产小时数：
              <el-input-number
                v-model="row.workHours"
                :min="1"
                :step="1"
                step-strictly
                size="small"
                :disabled="disabled"
              ></el-input-number>
              小时
              <el-button
                v-if="!disabled"
                type="text"
                class="remove-btn"
                @click="removeParticipant(row)"
                >移除</el-button
              >
            </el-col>
          </el-row>
        </template>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          v-if="!disabled"
          :loading="saveLoading"
          type="default"
          @click="handleSubmit('preserve')"
          >暂存</el-button
        >
        <el-button
          v-if="!disabled"
          :loading="saveLoading"
          type="primary"
          @click="handleSubmit('complete')"
          >提交</el-button
        >
      </span>
    </el-dialog>
    <!-- 选择参与人弹框 -->
    <userList
      :visibles.sync="userDialog.visible"
      :multiple="true"
      :defaultValues="userDialog.defaultLineUsers"
      :branchinnercode="userDialog.branchinnercode"
      branchinnerKey="code"
      @closeDialog="closeUserDialog"
    ></userList>
    <!-- 转办 -->
    <TransferDailog
      :visible.sync="transferDailog.visible"
      :row="transferDailog.row"
      @refresh="handleSubmitTransfer"
    ></TransferDailog>
  </div>
</template>
<script>
import FillForm from "../fillForm";
import TransferDailog from "../transferTaskDialog";
import {
  getTaskDetail,
  saveTaskContent,
  getTaskContent,
  getTaskTemplateByTaskId,
} from "@/api/taskMgmt/center";
import { checkPermi } from "@/utils/permission";
import { mapGetters } from "vuex";
export default {
  components: { FillForm, TransferDailog },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      taskDetail: null,
      templateConfig: null,
      formData: null,
      formWorkOrder: null,
      // 参与人
      participants: [],
      userDialog: {
        visible: false,
        branchinnercode: null,
        defaultLineUsers: [],
      },
      transferDailog: {
        visible: false,
        row: null,
      },
      loading: false,
      saveLoading: false,
    };
  },
  computed: {
    ...mapGetters(["realname"]),
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    formName() {
      return this.row?.taskName || "";
    },
    renderingMode() {
      return this.row?.renderingMode || "1";
    },
    headerForm() {
      const data = this.taskDetail;
      if (!data) {
        return {
          ownedFactory: null,
          ownedFactoryName: null,
          ownedWorkshopId: null,
          ownedWorkshopName: null,
          ownedProductionLineId: null,
          ownedProductionLineName: null,
          groupId: null,
          groupName: null,
          className: null,
          executorName: null,
          auditorName: null,
          date: this.parseTime(new Date(), "{y}-{m}-{d}"),
          actualExecuteStartTime: null,
          actualExecuteEndTime: null,
        };
      }
      return {
        ownedFactory: data.ownedFactory,
        ownedFactoryName: data.ownedFactoryName,
        ownedWorkshopId: data.ownedWorkshopId,
        ownedWorkshopName: data.ownedWorkshopName,
        ownedProductionLineId: data.ownedProductionLineId,
        ownedProductionLineName: data.ownedProductionLineName,
        groupId: data.groupId,
        groupName: data.groupName,
        className: data.className,
        executorName: this.realname,
        auditorName: data.auditorName,
        date: this.parseTime(new Date(), "{y}-{m}-{d}"),
        actualExecuteStartTime: data.actualExecuteStartTime,
        actualExecuteEndTime: data.actualExecuteEndTime,
      };
    },
    needParticipant() {
      return ["4", "5"].includes(this.taskDetail?.taskType);
    },
  },
  methods: {
    // 列表按钮显示权限
    buttonPermi(permis, flag) {
      return checkPermi(permis) && flag;
    },
    handleClose() {
      this.templateConfig = {};
      this.formData = null;
      this.formWorkOrder = null;
      this.participants = [];
    },
    handleOpen() {
      // 查询任务详情
      this.getTaskDetail();

      // 待执行的任务，不需要查询详情，还没有保存过表单
      if (this.row?.status == "0") {
        this.getTemplateConfig();
      } else {
        // 获取任务模板的单据设计和表单填报内容
        this.getTemplateAndContent();
      }
    },
    // 获取任务详情
    getTaskDetail() {
      if (!this.row?.id) {
        return;
      }
      getTaskDetail(this.row.id)
        .then((res) => {
          this.taskDetail = res?.data || null;
        })
        .catch(() => {
          this.taskDetail = null;
        });
    },
    // 任务模板的单据设计 以及 表单填报内容
    getTemplateAndContent() {
      if (!this.row?.id) {
        return;
      }
      this.loading = true;
      Promise.all([
        getTaskTemplateByTaskId(this.row.id),
        getTaskContent({ missionCenterId: this.row.id }),
      ])
        .then(([res1, res2]) => {
          // 任务模板的单据设计
          if (res1?.data && res1?.data != "null") {
            this.templateConfig = JSON.parse(res1.data);
          } else {
            this.templateConfig = null;
          }
          // 填报内容
          this.participants =
            res2?.data?.taskParticipantList?.map((ele) => ({
              id: ele.id,
              username: ele.participant,
              realname: ele.participantName,
              workHours: ele.participationDuration,
            })) || [];
          this.formData = res2?.data?.taskContentDtoList || [];
          this.formWorkOrder = {
            workOrderNo: res2?.data?.workOrderNo,
            workOrderName: res2?.data?.workOrderName,
          };
        })
        .catch(() => {
          this.templateConfig = null;
          this.formData = null;
          this.formWorkOrder = null;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取任务模板的单据设计
    getTemplateConfig() {
      if (!this.row?.id) {
        return;
      }
      this.loading = true;
      getTaskTemplateByTaskId(this.row.id)
        .then((res) => {
          if (res?.data && res?.data != "null") {
            this.templateConfig = JSON.parse(res.data);
          } else {
            this.templateConfig = null;
          }
          this.loading = false;
        })
        .catch(() => {
          this.templateConfig = null;
          this.loading = false;
        });
    },
    getOperatorLabel(form) {
      // if (form.operatorType == "dept") {
      //   // 显示部门
      //   return form.executiveAgencyName || form.executiveAgency;
      // }
      // let operatorName = form.operatorName;
      // if (this.postManageDictObj.hasOwnProperty(form.operator)) {
      //   // 显示岗位
      //   operatorName = this.postManageDictObj[form.operator];
      // } else {
      //   // 显示工位
      //   operatorName = form.operatorName;
      // }
      // return operatorName || "";
    },
    // 添加参与人
    addParticipant() {
      this.userDialog.defaultLineUsers = this.participants.map((ele) => ({
        username: ele.username,
        realname: ele.realname,
      }));
      this.userDialog.branchinnercode = this.headerForm.ownedFactory;
      this.userDialog.visible = true;
    },
    closeUserDialog(list) {
      let _participants = [];
      list.forEach((ele) => {
        const item = this.participants.find((u) => u.username == ele.username);
        _participants.push({
          username: ele.username,
          realname: ele.realname,
          workHours: item?.workHours || 1,
        });
      });
      this.participants = _participants;
    },
    // 移除参与人
    removeParticipant(row) {
      this.participants = this.participants.filter(
        (ele) => ele.username != row.username
      );
    },
    handleSubmit(execStatus) {
      if (this.disabled) {
        return
      }
      // 针对任务类型为“非生产类任务、计划停机任务”的任务，需上报参与人及工时，至少保留一行。
      if (this.needParticipant && !this.participants.length) {
        this.msgWarning(
          "“非生产类任务、计划停机任务”的任务，需上报参与人及工时!"
        );
        return;
      }
      // 暂存不做表单校验，执行提交时做必填校验
      const submitResult = this.$refs.FillForm.getSubmitData(
        execStatus == "complete"
      );

      if (!submitResult) {
        return;
      }

      // 校验
      const emtyWorkHours = this.participants.find(
        (ele) => !ele.workHours || ele.workHours == "0"
      );
      if (emtyWorkHours) {
        this.msgError("请输入工时！");
        return;
      }

      const {
        taskContentDtoList,
        workOrderNo,
        groupId,
        groupName,
        className,
        classId,
      } = submitResult;

      let taskParticipantList = this.participants.map((ele) => ({
        participant: ele.username,
        participationDuration: ele.workHours,
      }));

      const params = {
        missionCenterId: this.row.id,
        execStatus,
        execResult: null,
        workOrderNo,
        taskContentDtoList,
        taskParticipantList,
        classStartTime: this.row.classStartTime,
        classEndTime: this.row.classEndTime,
        className,
        classId,
        groupId,
        groupName,
      };

      // 提交时需要二次确认,暂存不需要
      if (execStatus == "complete") {
        this.$confirm("是否确认提交表单？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.toSubmit(params);
          })
          .catch(() => {});
      } else {
        this.toSubmit(params);
      }
    },
    toSubmit(params) {
      this.saveLoading = true;
      saveTaskContent(params)
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("保存成功！");
            this.$emit("refresh");
            this.dialogVisible = false;
          }
        })
        .finally(() => {
          this.saveLoading = false;
        });
    },
    /** 转办按钮操作 */
    handleTransfer() {
      this.transferDailog.row = this.row;
      this.transferDailog.visible = true;
    },
    // 转办完
    handleSubmitTransfer() {
      this.$emit("refresh");
      this.dialogVisible = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.el-row {
  margin-top: 10px;
  font-size: 15px;
  display: flex;
  align-items: center;
  .remove-btn {
    margin-left: 10px;
  }
}
::v-deep .el-dialog__body {
  padding-bottom: 0;
}
.dialog-content {
  position: relative;
  width: 100%;
  .transfer-btn {
    position: absolute;
    right: 0;
    top: 0;
  }
}
</style>
